package com.meiyu.live.ui.main;

import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseFragment;
import com.meiyu.live.R;
import com.meiyu.live.comm.Constant;
import com.meiyu.live.net.param.BaseBodyParams;
import com.meiyu.live.net.param.GetGiftsParams;
import com.meiyu.live.net.response.GifeDetailResponse;
import com.meiyu.live.net.response.LiveGiftResponse;
import com.meiyu.live.popj.GiftForLive;
import com.meiyu.live.widget.MSGView;
import com.meiyu.live.widget.NetLoadingDailog;

import java.util.HashMap;
import java.util.Map;

/**
 * 主播资料
 * Created by zbl on 2016/9/22.
 */
public class GetGiftsFragment extends BaseFragment implements View.OnClickListener {


    private NetLoadingDailog dialog_loading;

    private ListView listView;
    private LayoutInflater inflater;
    private SwipeRefreshLayout refreshLayout;
    private DataListAdapter adapter;
    private View footerView;
    private MSGView msgView;

    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private static final int PAGE_SIZE = 10;
    private int index = 1;
    long anchor_id;
    private boolean hasMore = true;
    public static int TYPE_RANK = 0;
    public static int TYPE_DETAIL = 1;
    private int type = 1;
    private Map<String, String> gift_Category = new HashMap();
    private GifeDetailResponse data = new GifeDetailResponse();

    public static GetGiftsFragment start(long anchor_id, int type) {
        GetGiftsFragment fragment = new GetGiftsFragment();
        fragment.initDate(anchor_id, type);
        return fragment;
    }

    public void initDate(long anchor_id, int type) {
        this.type = type;
        this.anchor_id = anchor_id;
    }

    @Override
    public int getContextView() {
        return R.layout.fragment_giftdetail;
    }


    @Override
    protected void init() {
        dialog_loading = new NetLoadingDailog(getActivity());

        inflater = LayoutInflater.from(getActivity());
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        msgView = (MSGView) findViewById(R.id.msgView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(true);
            }
        });
        listView = (ListView) findViewById(R.id.listview);

        footerView = inflater.inflate(R.layout.view_loadmore, null);
        listView.addFooterView(footerView);
        footerView.setVisibility(View.GONE);

        adapter = new DataListAdapter();
        listView.setAdapter(adapter);
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { // 判断滚动到底部
                    if (absListView.getLastVisiblePosition() == (absListView.getCount() - 1) && hasMore) {
                        footerView.setVisibility(View.VISIBLE);
                        getData(false);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        getData(true);
    }


    @Override
    public void onClick(View view) {
    }


    @Override
    public void onError() {
        super.onError();
        dialog_loading.dismissDialog();
    }

    private void getData(final boolean reload) {
        msgView.showLoading();
        if (reload) {
            index = 1;
            hasMore = true;
        }
        if (type == TYPE_DETAIL) {
            BaseBodyParams b = new BaseBodyParams();
            b.setUrl(Constant.UrlParams.LIVEGIFTS);
            request(b, LiveGiftResponse.class, new Response.Listener<LiveGiftResponse>() {
                @Override
                public void onResponse(LiveGiftResponse liveGiftResponse) {
                    if (liveGiftResponse.getHash() != null && liveGiftResponse.getHash().size() > 0) {
                        for (GiftForLive giftForLive : liveGiftResponse.getHash()) {
                            gift_Category.put(giftForLive.getId() + "", giftForLive.getName());
                        }
                        getGifts(reload);
                    }
                }
            });
        } else {
            getGifts(reload);
        }


    }

    private void getGifts(final boolean reload) {
        int area[] = {PAGE_SIZE, index + PAGE_SIZE - 1};
        GetGiftsParams gp = new GetGiftsParams(anchor_id, area);
        if (type == TYPE_DETAIL) {
            gp.setUrl(Constant.UrlParams.VIEWDETAIL);
        } else {
            gp.setUrl(Constant.UrlParams.VIEWRANK);
        }

        request(gp, GifeDetailResponse.class, new Response.Listener<GifeDetailResponse>() {
            @Override
            public void onResponse(GifeDetailResponse gifeDetailResponse) {
                if (gifeDetailResponse.getHash() != null) {
                    refreshLayout.setRefreshing(false);
                    footerView.setVisibility(View.GONE);
                    if (gifeDetailResponse != null) {
                        if (reload) {
                            data.getHash().clear();
                        }
                        data.getHash().addAll(gifeDetailResponse.getHash());
                        index += PAGE_SIZE;
                        if (gifeDetailResponse.getHash().size() < PAGE_SIZE) {
                            hasMore = false;
                        }
                        adapter.notifyDataSetChanged();
                        if (data.getHash().size() == 0) {
                            msgView.show_empty();
                        } else {
                            msgView.dismiss();
                        }
                    } else {
                        msgView.show_error();
                    }
                }
            }
        });
    }

    class DataListAdapter extends BaseAdapter {

        private class ViewHolder {
            ImageView iv_avatar;
            TextView tv_name, tv_level, tv_total;
        }


        @Override
        public int getCount() {
            return data != null && data.getHash() != null ? data.getHash().size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_giftdetail, null);
                holder = new ViewHolder();
                holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_level = (TextView) convertView.findViewById(R.id.tv_level);
                holder.tv_total = (TextView) convertView.findViewById(R.id.tv_total);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            GifeDetailResponse.GiftDetail bean = data.getHash().get(position);
            imageLoader.displayImage(bean.getAvatar(), holder.iv_avatar, options);
            holder.tv_name.setText(bean.getName());
            String level = bean.getLevel() + "";
            holder.tv_level.setText(TextUtils.isEmpty(level) ? "1" : level);
            if (type == TYPE_DETAIL) {
                holder.tv_total.setText("赠送" + bean.getGift_counts() + "个" + gift_Category.get(bean.getGift_ids()));
            } else {
                holder.tv_total.setText("赠送" + bean.getTotal() + "鱼粮");
            }

            return convertView;
        }
    }

}
